﻿using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using System.Text;
using System.Threading.Tasks;
using xiaoxiong.KYJDAL.MyDbcontext;
using thinger.DataConvertLib;

namespace xiaoxiong.KYJDAL.Services
{
    public class MysqlService
    {
        kyjDbContext  kyjDbContext = new kyjDbContext();

        /// <summary>
        /// 查看数据库是否有当前表名
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public bool IsTableExits(string tableName)
        {
            var tables = kyjDbContext.Db.DbMaintenance.GetTableInfoList(false);
            foreach (DbTableInfo item in tables)
            {
                if (item.Name == tableName)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 删除当前表
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private bool DeleteTable(string tableName)
        {
            return kyjDbContext.Db.DbMaintenance.DropTable(tableName);
        }

        /// <summary>
        /// 清除表数据内存
        /// </summary>
        /// <returns></returns>
        private bool VacuumTable(string tableName)
        {
            try
            {
                kyjDbContext.Db.Ado.ExecuteCommand($"OPTIMIZE TABLE {tableName};");
                return true;
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="colums"></param>
        /// <param name="IsPrimaryKey"></param>
        /// <returns></returns>
        private bool CreateTable(string tableName, List<string> colums, bool IsPrimaryKey = true)
        {

            try
            {
                // 动态构建实体类
                var dynamicBuilder = kyjDbContext.Db.DynamicBuilder()
                    .CreateClass(tableName, new SugarTable()
                    {
                        TableName = tableName, // 显式设置表名
                        TableDescription = "动态创建的表"  // 可选：表注释
                    });

                // 遍历列名列表，动态添加属性（列）
                for (int i = 0; i < colums.Count; i++)
                {
                    string columnName = colums[i];
                    Type columnType;
                    SugarColumn columnAttribute;

                    // 默认第一个列为主键（若 IsPrimaryKey=true）
                    if (i == 0 && IsPrimaryKey)
                    {
                        columnType = typeof(int);  // 主键默认为 int 类型
                        columnAttribute = new SugarColumn()
                        {
                            IsPrimaryKey = true,
                            IsIdentity = true,     // 自增
                            ColumnName = columnName,
                            ColumnDescription = "主键列"  // 可选：列注释
                        };
                    }
                    else
                    {
                        columnType = typeof(string);  // 非主键列默认为 string 类型
                        columnAttribute = new SugarColumn()
                        {
                            ColumnName = columnName,
                            Length = 200,              // 默认长度 200
                            ColumnDescription = "普通列"  // 可选：列注释
                        };
                    }

                    // 添加列到动态类
                    dynamicBuilder.CreateProperty(columnName, columnType, columnAttribute);
                }

                // 生成实体类型并创建表
                var entityType = dynamicBuilder.BuilderType();
                kyjDbContext.Db.CodeFirst.InitTables(entityType);

                return true;
            }
            catch (Exception ex)
            {
                // 处理异常（例如表已存在、列名非法等）
                Console.WriteLine($"创建表失败: {ex.Message}");
                return false;
            }
        }


        /// <summary>
        ///  创建数据表
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public OperateResult ReCreateActualTable(string tableName, List<string> columns)
        {
            if (IsTableExits(tableName))
            {
                if (DeleteTable(tableName) == false)
                {
                    return OperateResult.CreateFailResult("删除数据表失败" +  tableName);
                }
            }

            //创建
            if (CreateTable(tableName, columns) == false)
            {
                return OperateResult.CreateFailResult("创建数据表失败" + tableName);
            }
            VacuumTable(tableName);
            //创建成功
            return OperateResult.CreateSuccessResult("创建成功");
        }
    }
}
